package heman.server.controllers;

import heman.server.entities.Player;
import heman.server.entities.PlayerManager;
import heman.server.entities.Table;
import heman.server.entities.TableManager;
import heman.server.entities.TableType;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.server.interfaces.IProcessServerMessage;

/**
 * Leave controller handles LEAVE message.
 * <xs:element name="leave">
 * 	<xs:complexType>
 * 		<xs:attribute name="table" type="table-id" use="required" /> 
 * 		<xs:attribute name="player" type="valid-player-id" use="optional" /> 
 * 	</xs:complexType>
 * </xs:element>
 * 
 * @author Yanyi Zhang
 * 
 */
public class LeaveController implements IProcessServerMessage{
	public boolean process(Communicator com, Message m){
		String originator=m.getOriginator();
		NamedNodeMap map=m.contents().getAttributes();
		String tableID=map.getNamedItem("table").getNodeValue();
		Player TargetPlayer;
		if(map.getNamedItem("player")==null)//if leave voluntarily
			TargetPlayer=PlayerManager.getInstance().getPlayer(originator);
		else
			TargetPlayer=PlayerManager.getInstance().getPlayer(map.getNamedItem("player").getNodeValue());
		Table TargetTable=TableManager.getInstance().getTable(tableID);
		String moderator=TargetTable.getModerator().getId();
		if(TargetTable.getType().equals(TableType.IN_PLAY)){//if the game is in play
			TargetTable.exit(TargetPlayer);
		}
		else if(originator.equals(moderator)){//if the player is the moderator
			if(TargetTable.getPlayerIDs().size()==1)//if it's the only player on table
				TargetTable.resetTable();
			else {
				TargetTable.removePlayer(TargetPlayer);
				TargetTable.setModerator(PlayerManager.getInstance().getPlayer(TargetTable.getPlayerIDs().get(0)));
			}
		}
		else{//if the player is not moderator
			TargetTable.removePlayer(TargetPlayer);
		}
		Message r;
		StringBuilder sb = new StringBuilder(Message.responseHeader(true,m.id));
		if(TargetTable.getPlayerIDs().size()==0){//if the table has been reseted
			sb.append("<tableEmpty table='");
			sb.append(tableID);
			sb.append("'/></response>");
		}
		else{
			sb.append("<tableResponse>");
	        sb.append(TargetTable.toXML());
	        sb.append("</tableResponse></response>");
		}
        Document d = Message.construct(sb.toString());
        r = new Message (d);
        r.setOriginator(originator);
        r.setRecipient(originator);//respond to originator
        r.setBroadcast();//respond to others
        return com.distribute(r);
	}
}
